import { fromJS } from "immutable";
import { AnyAction } from "redux";
import { handleActions } from "redux-actions";
import { combineReducers } from "redux-immutable";
import {
  LOGIN,
  LOGOUT,
  SET_DOCTOR_LIST,
  SET_HOSPITAL_LIST
} from "../AcrionTypes";
/**
 * 处理医院数据的reducer
 * @description handleActions
 */
const hospitalReducer = handleActions<any>(
  {
    [SET_HOSPITAL_LIST]: (state, action: AnyAction) => {
      return state.set("hospitalList", fromJS(action.payload));
    }
  },
  fromJS({
    hospitalList: []
  })
);
/**
 * 处理医生数据的reducer
 */
const doctorReducer = handleActions<any>(
  {
    [SET_DOCTOR_LIST]: (state, action: AnyAction) => {
      return state.set("doctorList", fromJS(action.payload));
    }
  },
  fromJS({ doctorList: [] })
);
/**
 * 登录或退出
 */
const loginOrLogoutReducer = handleActions<any>(
  {
    [LOGIN]: (state, action: AnyAction) => {
      return state.set("user", fromJS(action.payload));
    },
    [LOGOUT]: (state, action: AnyAction) => {
      return state.set("user", fromJS({}));
    }
  },
  fromJS({ user: {} })
);
/**
 * redux-immutable提供一个combineReducers()函数，
 * 将stroe中最外层的reducer中的state转化为immutable对象
 * （这里涉及到reducer的拆分，拆分用到了与redux中同名的combineReducers()方法
 */
export default combineReducers({
  hospitalReducer,
  doctorReducer,
  loginOrLogoutReducer
});
